
import { sys, _decorator, Component, Sprite, Label, lerp, assetManager, UITransform, Node } from "cc";
import { EDITOR } from "cc/env";
import { initData } from "./GameDefine";


// 加载主包
let isEnter = false;
(function () {
    if (EDITOR)
        return
    if (isEnter)
        return
    isEnter = true

    let _wx = (window as any)["wx"]
    if (_wx && _wx.startRenderDestroy)
        _wx.startRenderDestroy()

    console.log("load bundle main " + Date.now())
    assetManager.loadBundle("main2")
})();


// cc启动脚本
const { ccclass, property, menu } = _decorator;

const textStr = [
    "加载中",
    "加载中·",
    "加载中··",
    "加载中···",
]


@ccclass("App")
@menu("App")
export class App extends Component {

    private ratioSprite: Sprite = null!
    private ratioNum = 0
    private ratioTransform: UITransform = null!
    private topTextLab: Label = null!
    private textTime = 0
    private textIndex = 0
    private followRatioNode: Node = null!

    onLoad() {
        let loading = this.node.getChildByName("Loading")!
        let ratio = loading.getChildByName("Ratio")!

        this.topTextLab = ratio.getChildByName("TopText")!.getComponent(Label)!
        this.topTextLab.node.active = initData.showLoadingText

        let dec = loading.getChildByName("BottomDec")!
        if (initData.versionId && initData.showLoadingText) {
            dec.active = true
            dec.getComponentInChildren(Label)!.string = initData.versionId
        }
        else
            dec.active = false

        loading.getChildByName("Age")!.active = initData.showLoadingText

        let Bg = ratio.getChildByName("Bg")!
        this.ratioSprite = Bg.getChildByName("Ratio")!.getComponent(Sprite)!
        this.ratioTransform = this.ratioSprite.getComponent(UITransform)!

        this.followRatioNode = Bg.getChildByName("FollowRatio")!

        this.updateWidthAndPosition()
    }

    updateWidthAndPosition() {
        // 计算新的宽度并设置
        const baseWidth: number = 39; // 基础宽度
        const segments: number = Math.ceil(543 / baseWidth); // 将543分段为基础宽度块数
        this.ratioTransform.width = Math.floor(this.ratioNum * (segments + 1)) * baseWidth; // 更新宽度

        // 如果跟随节点存在，则更新其位置
        if (this.followRatioNode) {
            this.followRatioNode.setPosition(543 * (this.ratioNum - 0.5), 0); // 更新位置
        }
    }


    protected update(dt: number): void {
        // 2秒
        this.ratioNum = lerp(this.ratioNum, 1, .005)
        this.updateWidthAndPosition()

        this.textTime += dt
        if (this.textTime > 0.5) {
            this.textTime = 0
            this.topTextLab.string = textStr[this.textIndex % textStr.length]
            this.textIndex++
        }
    }

}


